from collections.abc import Iterable


class MyList:
    def __init__(self):
        self.container = []

    def add(self, item):
        self.container.append(item)

    # 只要重写了iter方法，就会变为可迭代的,iter必须返回一个迭代器
    def __iter__(self):
        myiterator = MyIterator(self)
        return myiterator


class MyIterator:
    def __init__(self, mylist):
        self.mylist: MyList = mylist
        self.current = 0

    def __next__(self):
        current = self.current
        self.current += 1
        if current < len(self.mylist.container):
            return self.mylist.container[current]

        else:
            raise StopIteration

    def __iter__(self):
        return self


# if __name__ == '__main__':
#     mylist=MyList()
#     mylist.add(1)
#     mylist.add(2)
#     mylist.add(3)
#     # print(isinstance(mylist,Iterable))
#     for i in mylist:
#         print(i)
#
#     my_iter=iter(mylist)
#     print(next(my_iter))
#     print(next(my_iter))
#     print(next(my_iter))
#     # print(next(my_iter))
#     # print(next(my_iter))


def test():
    list1 = [1, 2, 3, 4]
    iter1 = iter(list1)
    print(next(iter1))  # 1
    print(next(iter1))  # 2
    print(next(iter1))  # 3
    print(next(iter1))  # 4
    print(next(iter1))  # StopIteration


test()
